package com.yenlien.traceyun.control.service;

import com.yenlien.traceyun.control.dao.NewsDao;
import com.yenlien.traceyun.control.entity.News;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class NewsService {

    @Autowired
    private NewsDao newsDao;

    /**
     * 查询消息
     *
     * @param page
     * @return
     */
    public Page<News> select(Integer page) {
        Sort ageSort = Sort.by(Sort.Direction.DESC, "newsTime");
        PageRequest pageRequest = PageRequest.of(page, 10, ageSort);
        Page<News> all = newsDao.findAll(pageRequest);
        return all;
    }


    public void add(News news) {
        if (news != null) {
            if (news.getHeadline() == null || "".equals(news.getHeadline())) {
                throw new BusinessException("500", "headline标题不能为空");
            }
            if (news.getContent() == null || "".equals(news.getContent())) {
                throw new BusinessException("500", "content内容不能为空");
            }
            newsDao.save(news);
            if (news.getId() == null) {
                throw new BusinessException("500", "添加失败");
            }
        }
    }

    public void del(String id) {
        News news = new News();
        news.setId(id);
        newsDao.delete(news);
    }

}
